import pathlib
import time
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *









SCRIPT_JAVAS = """
// ==UserScript==
// @name         淘宝-搜同款【获取】【标题|主图链接】
// @namespace    http://tampermonkey.net/
// @version      0.9
// @description  点击按钮获取当前页面中所有 .title--qJ7Xg_90 元素的文本并展示在文本编辑器中，以及获取指定img的src链接
// @author       你自己的名字
// @match        *://s.taobao.com/*
// @grant        none
// ==/UserScript==

// match是用来匹配网址是否加载的.
// @match 支持的匹配规则使用的是类似于 scheme://host/path 的格式
// 其中 scheme 是协议（如 http、https 等）
// host 是域名，path 是路径。你可以使用通配符 * 来匹配任意字符序列。

(function () {
    'use strict';

    // 创建按钮容器
    const buttonGroup = document.createElement('div');
    buttonGroup.style.position = 'fixed';
    buttonGroup.style.top = '10px';
    buttonGroup.style.left = '10px';
    buttonGroup.style.zIndex = '9999';
    buttonGroup.style.display = 'flex';
    buttonGroup.style.gap = '10px';
    // 为按钮容器添加背景颜色，这里使用浅灰色作为示例
    buttonGroup.style.backgroundColor = '#f0f0f0';
    // 添加内边距，让按钮与容器边缘有一定距离
    buttonGroup.style.padding = '10px';
    // 添加圆角
    buttonGroup.style.borderRadius = '4px';

    // 创建获取文本按钮
    const getTextButton = document.createElement('button');
    getTextButton.textContent = '获取 所有标题 文本';
    getTextButton.style.backgroundColor = '#4CAF50'; // 绿色背景
    getTextButton.style.color = 'white';
    getTextButton.style.fontSize = '25px';
    getTextButton.style.padding = '10px 20px';
    getTextButton.style.border = 'none';
    getTextButton.style.borderRadius = '4px';
    getTextButton.style.cursor = 'pointer';

    // 创建获取img src链接按钮
    const getImgSrcButton = document.createElement('button');
    getImgSrcButton.textContent = '获取img src链接';
    getImgSrcButton.style.backgroundColor = '#008CBA'; // 蓝色背景
    getImgSrcButton.style.color = 'white';
    getImgSrcButton.style.fontSize = '25px';
    getImgSrcButton.style.padding = '10px 20px';
    getImgSrcButton.style.border = 'none';
    getImgSrcButton.style.borderRadius = '4px';
    getImgSrcButton.style.cursor = 'pointer';

    // 将按钮添加到按钮组中
    buttonGroup.appendChild(getTextButton);
    buttonGroup.appendChild(getImgSrcButton);

    // 将按钮组添加到页面中
    document.body.appendChild(buttonGroup);

    let textarea;

    // 为获取文本按钮添加点击事件监听器
    getTextButton.addEventListener('click', function () {
        // 若文本框已存在，先移除
        if (textarea) {
            textarea.remove();
        }
        // 获取所有 div#content_items_wrapper > div 元素
        const contentWrappers = document.querySelectorAll('div#content_items_wrapper > div');

        contentWrappers.forEach((wrapper) => {
            // 在每个 wrapper 里查找 .title--qJ7Xg_90 元素
            const titleElement = wrapper.querySelector('.title--ASSt27UY');
            if (titleElement) {
                const text = titleElement.textContent;
                const copyButton = document.createElement('button');
                copyButton.textContent = '复制标题';
                copyButton.style.backgroundColor = '#008CBA';
                copyButton.style.color = 'white';
                copyButton.style.fontSize = '18px';
                copyButton.style.padding = '10px 20px';
                copyButton.style.border = 'none';
                copyButton.style.borderRadius = '4px';
                copyButton.style.cursor = 'pointer';
                copyButton.style.marginLeft = '10px';
                copyButton.addEventListener('click', function () {
                    const tempInput = document.createElement('input');
                    tempInput.value = text;
                    document.body.appendChild(tempInput);
                    tempInput.select();
                    document.execCommand('copy');
                    document.body.removeChild(tempInput);

                    // 创建提示框
                    const toast = document.createElement('div');
                    // 修改提示信息，分行显示
                    toast.innerHTML = `标题复制成功：<br>${text}`; 
                    toast.style.position = 'fixed';
                    toast.style.top = '50%';
                    toast.style.left = '50%';
                    toast.style.transform = 'translate(-50%, -50%)';
                    toast.style.backgroundColor = '#333';
                    toast.style.color = 'white';
                    toast.style.padding = '20px 40px';
                    toast.style.borderRadius = '4px';
                    toast.style.zIndex = '9999';
                    toast.style.fontSize = '24px';
                    document.body.appendChild(toast);

                    // 3秒后自动移除提示框
                    setTimeout(() => {
                        toast.remove();
                    }, 3000);
                });
                wrapper.appendChild(copyButton);
            }
        });
    });

    // 为获取img src链接按钮添加点击事件监听器
    getImgSrcButton.addEventListener('click', function () {
        // 获取所有 div#content_items_wrapper > div 元素
        const contentWrappers = document.querySelectorAll('div#content_items_wrapper > div');

        contentWrappers.forEach((wrapper) => {
            // 在每个 wrapper 里查找指定路径的 img 元素
            const imgElement = wrapper.querySelector("div[class*='imageSwitch--fJ9SrtEb '] img");
            if (imgElement) {
                const imgSrc = imgElement.src;
                const copyImgButton = document.createElement('button');
                copyImgButton.textContent = '复制图片链接';
                copyImgButton.style.backgroundColor = '#008CBA';
                copyImgButton.style.color = 'white';
                copyImgButton.style.fontSize = '18px';
                copyImgButton.style.padding = '10px 20px';
                copyImgButton.style.border = 'none';
                copyImgButton.style.borderRadius = '4px';
                copyImgButton.style.cursor = 'pointer';
                copyImgButton.style.marginLeft = '10px';
                copyImgButton.addEventListener('click', function () {
                    const tempInput = document.createElement('input');
                    tempInput.value = imgSrc;
                    document.body.appendChild(tempInput);
                    tempInput.select();
                    document.execCommand('copy');
                    document.body.removeChild(tempInput);

                    // 创建提示框
                    const toast = document.createElement('div');
                    toast.innerHTML = `图片链接复制成功：<br>${imgSrc}`; 
                    toast.style.position = 'fixed';
                    toast.style.top = '50%';
                    toast.style.left = '50%';
                    toast.style.transform = 'translate(-50%, -50%)';
                    toast.style.backgroundColor = '#333';
                    toast.style.color = 'white';
                    toast.style.padding = '20px 40px';
                    toast.style.borderRadius = '4px';
                    toast.style.zIndex = '9999';
                    toast.style.fontSize = '24px';
                    document.body.appendChild(toast);

                    // 3秒后自动移除提示框
                    setTimeout(() => {
                        toast.remove();
                    }, 3000);
                });
                wrapper.appendChild(copyImgButton);
            }
        });
    });
})();    

"""


def Find_MainImageTitle(driver:WebDriver,Picture_Path:str,Delay:float=5) -> None:
    """根据图片路径在淘宝网搜索同款!

    Args:
        driver (WebDriver): WebDriver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        Picture_Path (str): 图片路径
    """
    driver.switch_to.new_window("tab")
    driver.get(url="https://s.taobao.com/search?")
    
    try:
        wait_element_xpath_value = f"//div[@class='image-icon-text' and text()='搜同款']"
        WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath_value)))
    except TimeoutException:
        print(f"提示 : 网页加载失败!\n已退出!")
        return 
    
    try:
        target_element_xpath_value = f"//div[@class='image-icon-text' and text()='搜同款']"
        element = WebDriverWait(driver=driver,timeout=5).until(expected_conditions.visibility_of_element_located(locator=(By.XPATH,target_element_xpath_value)))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 获取元素失败!\n已退出!")
        return
    
    try:
        wait_element_xpath_value = f"//div[contains(@class,'image-search-context-wrapper-active')]//input[@type='file']"
    except TimeoutException:
        print(f"提示 : 打开上传图片对话框失败!\n已退出!")
        return

    try:
        target_element_xpath_value = f"//div[contains(@class,'image-search-context-wrapper-active')]//input[@type='file']"
        element = WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,target_element_xpath_value)))
        element.send_keys(pathlib.Path(Picture_Path).absolute().resolve().__str__())
    except TimeoutException:
        print(f"提示 : 没有找到可以上传图片的元素控件!\n已退出!")
        return
    
    try:
        wait_element_xpath_value  = f"//div[@id='image-search-upload-button' and text()='搜索']"
        WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,wait_element_xpath_value)))
    except TimeoutException:
        print(f"提示 : 图片上传失败!\n已退出!")
        return
    
    try:
        target_element_xpath_value = f"//div[@id='image-search-upload-button' and text()='搜索']"
        element = WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,target_element_xpath_value)))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到开始搜索同款的按钮!\n已退出!")
        return

    time.sleep(Delay)
    # driver.execute_script(open(file="./js/淘宝搜同款标题辅助文件.js",mode="r",encoding="utf-8").read())
    driver.execute_script(script=SCRIPT_JAVAS)
